package com.mk.cloud.common.util.pay;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.mk.cloud.common.domain.PCoconfig;
import com.mk.cloud.common.exception.UserException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Created by cb on 2017/05/18.
 */
//public class AppAliPayUtils {
public class AppAliPayUtils extends PayUtils {
    private final String apiUrl="https://openapi.alipay.com/gateway.do";
    private AlipayClient alipayClient;
    private final String orderQueryUrl = "https://openapi.alipay.com/gateway.do";

//    String alipay_app_id ="2017032206333534";
//    String alipay_app_private_key="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCSBcPbInE8ZWrqNwCr6CC64yfqbhI//JpSj+tKNFQpxTKnsLClM3DEYfhcX/GHL5wF/+Esv97zHzgb38zECs1w7SAqt3qX082Bbt18eYPLs7UmhhkV63LvBkl1/nu54mkFK/FcaOrrE8BFmKELI2kl8vNpON63DLZpJrs5d2dgg7rRI8sFY8DKfuhlM5m5VCj/DQ0iyRiQCc27pSV8mizZTSL7MRBIRml+g00hobo5GiCvg+FpN110KvpTca3YDa0JPS1QvUOvx79SdmVEYhkZp+apHbQMMwaaHlqYKM/vyffdidO+gI2pXvHsaYOAIf9u+5ytZwCFzz9qKb5fEMCLAgMBAAECggEAAn9ovznSmAbgEkuIjmg1Dx1NlHv3gfKvLRRbIPTOL7y4xheGnfzIRAOs/N+DQR22XH/o+Rv7E0uIaSml1gCdTP4xW6mxxiEQVdNwpG1rrLNROOx4R2C0oZQI86S7tw1BYJ5EzaDZy9WVp1sZ/hfH96c1NKqNXLIx+JB6CVyafxMbCnwU0EddoY7QLmKqhCAuUSFQSZocFnVJvYXPCfm/Nw1vyd5A7jYi+3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CyzF/yWACmBEgdbizuEHiFtMUBGTIX+lAZcqKD4E8xSBR6QK/IocOjQavloCIEyAnyIKL8vtow5VJQZbN5hRLWoc+DWKeWmsFJGYIr+inHj4NMD0R8IxAptEsHkvKS6/RSLw0sS5nQ3oStFeg3rFCeGmexJXJGI6E7bHQ1IAoAYHTeSjCZiJRYeg1eo/NgxltG9mRuuSPbt6xVvGAXAUtOhDipRE0ldS8huUdGVupkWHOAYbA/I+VdmRLd1w2fU6+y473fEbfNjMaTKD5h3ijt/okZfgUmSb3pqHhviv17DqrYMUkz2duf0BQveUQIDAQAB";
    String alipay_app_api_url="https://openapi.alipay.com/gateway.do";
    String alipay_app_charset="utf-8";
    String alipay_app_sign_type="RSA2";
    String alipay_app_notify_url="http://reg.emeker.com/pay/payAilResult.json";
    String alipay_app_return_url="http://gyh.emeker.com/mkshop/paycallback";
    String info_des = "test";

    private Properties props;

    public AppAliPayUtils(){
        try {
//            alipayClient = new DefaultAlipayClient(
//                    alipay_app_api_url,
//                    alipay_app_id,
//                    alipay_app_private_key,
//                    "json",
//                    alipay_app_charset,
//                    alipay_app_public_key,
//                    alipay_app_sign_type);
        } catch (Exception e) {
            throw new UserException(e.getMessage());
        }
    }

    public AppAliPayUtils(PCoconfig coconfig){
        try {
            alipayClient = new DefaultAlipayClient(
                    alipay_app_api_url,
                    coconfig.getAliappid(),
                    coconfig.getAliprivatekey(),
                    "json",
                    alipay_app_charset,
                    coconfig.getAlipublickkey(),
                    alipay_app_sign_type);
        } catch (Exception e) {
            throw new UserException(e.getMessage());
        }
    }

    @Override
    public Map<String, String> getPayObject(Map<String, String> map) {
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(map.get("body").toString()+props.getProperty("info_des"));
        model.setSubject(map.get("subject").toString()+props.getProperty("info_des"));
        model.setOutTradeNo(map.get("outTradeNo").toString());
        model.setTotalAmount(map.get("totalAmount").toString());
        model.setTimeoutExpress("30m");
        model.setProductCode("QUICK_MSECURITY_PAY");
        model.setGoodsType("0");
        model.setPassbackParams(map.get("passbackparams").toString());
        //model.setDisablePayChannels("point,voucher");//不支持积分支付
        request.setBizModel(model);
        // request.setNotifyUrl(map.get("basePath")+"/pay/payAilResult.json");//商户外网可以访问的异步地址
        request.setNotifyUrl(props.getProperty("alipay_app_notify_url"));//商户外网可以访问的异步地址
//        request.setNotifyUrl("http://kb.emeker.com/pay/payAilResult.json");

        //request.setReturnUrl("");
        Map<String, String> param = new HashMap<String, String>();
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            if (response.isSuccess()) {
                param.put("body", response.getBody());
                return param;
            } else {
                throw new UserException(response.getMsg());
            }

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return param;
    }
    public Map<String,String> getYue(){
        Map<String, String> param = new HashMap<String, String>();
        MybankFinanceYulibaoAccountQueryRequest request = new MybankFinanceYulibaoAccountQueryRequest();
        request.setBizContent("{" +
        "\"fund_code\":\"001529\"" +
        "  }");
        MybankFinanceYulibaoAccountQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            if(response.isSuccess()){
//            System.out.println("调用成功");
            } else {
//            System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return param;
    }
   /* public static void main(String[] args) {
        String body = "觅客直供-消费";
        String subject = "觅客直供";
        Map<String, String> map = new HashMap<>();
        map.put("body", body);
        map.put("subject", subject);
        map.put("outTradeNo", "WX2017121211111");
        map.put("totalAmount", 0.01 + "");
        map.put("passbackparams", "{ordertype:'OS',orderid:'sdf',userid:'123',username:'uuu',paytype:'2',giveid:'null'}");
        AppAliPayUtils a = new AppAliPayUtils();
        //a.getPayObject(map);
        a.getPayCodeUrl(map);
    }*/
    @Override
    public String getPayCodeUrl(Map<String, String> paramMap) {
        AlipayTradePrecreateRequest alipayRequest = new AlipayTradePrecreateRequest();
        //AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + paramMap.get("outTradeNo") + "\","
            + "\"total_amount\":\"" + paramMap.get("totalAmount") + "\","
            + "\"subject\":\"" + paramMap.get("subject")+props.getProperty("info_des") + "\","
            + "\"disable_pay_channels\":\"pcreditpayInstallment,point,voucher\","
            + "\"passback_params\":\""+paramMap.get("passbackparams")+"\","
            + "\"body\":\"" + paramMap.get("body")+props.getProperty("info_des") + "\"}");
        //+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        alipayRequest.setNotifyUrl(props.getProperty("alipay_app_notify_url"));//商户外网可以访问的异步地址
        String result = null;
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(alipayRequest);
            result = response.getQrCode();
//            AlipaySignature.rsaCheckV1(params, publicKey, charset,s);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 交易状态：trade_state 对应的值WAIT_BUYER_PAY（交易创建，等待买家付款）、TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、TRADE_SUCCESS（交易支付成功）、TRADE_FINISHED（交易结束，不可退款）
     *
     * @param payid
     * @return map trade_state:xxx,payid:xxx
     */
    @Override
    public Map<String, String> getOrderInfo(String payid) {
        Map<String, String> map = new HashMap<String, String>();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
            "\"out_trade_no\":\"" + payid + "\"" +
            "  }");
        AlipayTradeQueryResponse response;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                map.put("payid", payid);
                map.put("trade_state", response.getTradeStatus());
            } else {
                throw new UserException(response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public boolean closeOrder(String payid) {
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        request.setBizContent("{" +
//        "\"trade_no\":\"2013112611001004680073956707\"," +
            "\"out_trade_no\":\"" + payid + "\"" +
//        "\"operator_id\":\"YX01\"" +
            "  }");
        AlipayTradeCloseResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (response != null) {
            if (response.isSuccess()) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public Map<String, String> validatePayidState(String payid) {
        Map<String, String> map = new HashMap<String, String>();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +"\"out_trade_no\":\"" + payid + "\"" +"  }");
        AlipayTradeQueryResponse response;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                if(response.getTradeStatus().equals("TRADE_SUCCESS")){
                    map.put("flag","true");
                }else{
                    map.put("flag","false");
                }

            } else {
                map.put("flag","false");
            }
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 返回信息详见文档，有需要可获取
     * https://doc.open.alipay.com/doc2/apiDetail.htm?spm=a219a.7629065.0.0.PlTwKb&apiId=759&docType=4
     * out_trade_no payid支付id
     * trade_no 支付宝订单tradeno
     * refund_amount  refund_fee退款金额
     * refund_reason  reason 退款理由
     * out_request_no detailid明细id 若全部退款可不传
     */
    @Override
    public boolean refundOrder(Map<String, String> map) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
            "\"out_trade_no\":\"" + map.get("payid") + "\"," +
//        "\"trade_no\":\""+map.get("aofid")+"\"," +
            "\"refund_amount\":" + map.get("refund_fee") + "," +
            "\"refund_reason\":\"" + map.get("reason")+props.getProperty("info_des") + "\"," +
            "\"out_request_no\":\"" + map.get("detailid") + "\"" +
//        "\"operator_id\":\"OP001\"," +
//        "\"store_id\":\"NJ_S_001\"," +
//        "\"terminal_id\":\"NJ_T_001\"" +
            "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                return true;
            } else {
                throw new UserException(response.getSubMsg() + response.getMsg());
            }
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            throw new UserException("退款失败");
        }
    }

    @Override
    public String getSign(Map<String, String> map, String strType) {
        return null;
    }

    @Override
    public String getSignown(Map<String, Object> map, String strType) {
        return null;
    }

    /**
     * @param map 参数<br>
     *            https://doc.open.alipay.com/docs/api.htm?apiId=1321&docType=4<br>
     *            out_biz_no orderid 订单id 或者payid<br>
     *            payee_type payeetype ALIPAY_USERID/ALIPAY_LOGONID 必传<br>
     *            payee_account payeeaccount 支付宝唯一用户号。以2088开头的16位纯数字组成。 /支付宝登录号，支持邮箱和手机号格式。<br>
     *            amount amount 转账金额:元,最小值为0.1元,最多两位小数
     *            payee_real_name realname真实姓名<br>
     *            remark remark,
     *            payer_show_name:如果不传,则默认显示库窜犯改的支付宝认证姓名或单位名称
     * @return
     */
    @Override
    public String transfer(Map<String, Object> map) {
        //单笔转账到支付宝账户接口
        AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
        request.setBizContent("{" +
            "    \"out_biz_no\":\"" + map.get("payid") + "\"," +
            "    \"payee_real_name\":\"" + map.get("realname") + "\"," +
            "    \"payee_type\":\"" + map.get("payeetype") + "\"," +
            "    \"payee_account\":\"" + map.get("payeeaccount") + "\"," +
            "    \"amount\":\"" + map.get("amount") + "\"," +
//            "    \"payer_show_name\":\"觅客直供\"," +
            "    \"remark\":\"" + map.get("remark") + "\"" +
            "  }");
        AlipayFundTransToaccountTransferResponse response = null;
        try {
            response = alipayClient.execute(request);
            System.out.println(response.getBody());
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (response != null) {
            if (response.isSuccess()) {
                return "true";
            } else {
                return response.getSubMsg();
            }
        }
        return "false";
    }

    @Override
    public Map<String, Object> selTransfer(Map<String, Object> map) {
        return null;
    }

    @Override
    public String goWallet(Map<String, Object> map) {
        return null;
    }

    //


    @Override
    public Map<String, Object> payCallback(Map<String, String> map) {
        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, props.getProperty("alipay_app_public_key"),
                props.getProperty("alipay_app_charset"), props.getProperty("alipay_app_sign_type"));
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            signVerified = false;
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("payid", map.get("out_trade_no"));
        param.put("orderid", map.get("subject"));
        param.put("tradeno", map.get("trade_no"));
        param.put("passbackparams", map.get("passback_params"));
        param.put("signVerified", "false");
        param.put("trade_status", map.get("trade_status"));
        if (signVerified) {
            param.put("signVerified", "true");
            String out_trade_no = map.get("out_trade_no");
            String trade_no = map.get("trade_no");
        } else {
            throw new UserException("支付回调验证失败");
        }
        return param;
    }

    @Override
    public Map<String, String> getPayObjectGzh(Map<String, String> map) {
        Map<String,String> map1 = new HashMap<String,String>();

        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setBody(map.get("body").toString()+props.getProperty("info_des"));
        model.setSubject(map.get("subject").toString()+props.getProperty("info_des"));
        model.setOutTradeNo(map.get("outTradeNo").toString());
        model.setTotalAmount(map.get("totalAmount").toString());
        model.setTimeoutExpress("30m");
        model.setProductCode("QUICK_MSECURITY_PAY");
        model.setGoodsType("0");
        model.setPassbackParams(map.get("passbackparams").toString());
        alipayRequest.setNotifyUrl(props.getProperty("alipay_app_notify_url"));//商户外网可以访问的异步地址
        alipayRequest.setReturnUrl(props.getProperty("alipay_app_return_url"));//商户外网可以访问的前端地址
//        alipayRequest.setNotifyUrl("http://kb.emeker.com/pay/payAilResult.json");
//        alipayRequest.setReturnUrl("http://gyh.emeker.com/mkshop/paycallback");
        alipayRequest.setBizModel(model);

//        alipayRequest.setBizContent("{" +
//                "    \"out_trade_no\":\""+map.get("outTradeNo").toString()+"\"," +
//                "    \"total_amount\":"+map.get("totalAmount").toString()+"," +
//                "    \"subject\":\""+map.get("subject").toString()+"\"," +
//                "    \"product_code\":\"QUICK_WAP_WAY\"" +
////                "    \"body\":\""+map.get("body").toString()+"\"" +
////                "    \"subject\":\""+map.get("subject").toString()+"\"" +
////                "    \"passback_params\":\""+map.get("passbackparams").toString()+"\"" +
////                "    \"timeout_express\":\"30m\"" +
//                "  }");//填充业务参数
        try {
            String form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
            map1.put("form",form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return map1;
    }

    @Override
    public Map<String, String> getPayObjecth5(Map<String, String> paramMap) {
        return null;
    }
}
